package infolayer2.filter;

import infolayer2.graph.Graph;
import infolayer2.graph.Node;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class InfolayerXmlImport {

  String prefix;
  Graph graph;

  public InfolayerXmlImport(Graph graph, String prefix) {
    this.graph = graph;
    this.prefix = prefix;
  }

  public void process(InputStream is) throws SAXException, IOException, ParserConfigurationException {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
    process(doc.getDocumentElement());
  }
  
  public void process(Element root) {
    NodeList nodelist = root.getChildNodes();
    for (int i = 0; i < nodelist.getLength(); i++) {
      if (nodelist.item(i) instanceof Element) {
        processEntity((Element) nodelist.item(i));
      }
    }
  }
  
  private void processEntity(Element element) {
    String mid = element.getAttribute("id");
    Node entity = graph.getOrCreate(mid);
    
    String type = prefix + element.getNodeName();
    entity.addType(type);

    NodeList nodelist = element.getChildNodes();
    for (int i = 0; i < nodelist.getLength(); i++) {
      if (nodelist.item(i) instanceof Element) {
        processProperty(entity, type, (Element) nodelist.item(i));
      }
    }
  }

  private void processProperty(Node entity, String type, Element element) {
    String propertyName = type + "/" + element.getNodeName();

    String idref = element.getAttribute("idref");
    Object value;
    if (idref == null || "".equals(idref)) {
      value = element.getTextContent();
      if (!"".equals(value)) {
        entity.addValue(propertyName, value);
      }
    } else {
      entity.addReference(propertyName, idref);
    }
  }
}
